package com.baixiaowen.xiaoaointerview.并发基础篇;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;

/**
 *
 * 使用Phaser框架实现简单的CyclicBarrier
 *
 * @author Baixiaowen
 */
public class PhaserTest {

    Phaser phaser = new Phaser();

    ExecutorService executorService = Executors.newCachedThreadPool();

    class Worker implements Runnable {
        @Override
        public void run() {
            // 4 --- sync --- 4 --- sync --..
            phaser.register();

            while (true) {
                try {
                    Thread.sleep(500);
                    System.err.println("I'm working:@" + phaser.getPhase());
                    phaser.arriveAndAwaitAdvance();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void run() {
        // main thread
        phaser.register();
        executorService.execute(new Worker());
        executorService.execute(new Worker());
        executorService.execute(new Worker());
        executorService.execute(new Worker());

        while (true) {
            phaser.arriveAndAwaitAdvance();
            System.err.println("Sync......" + phaser.getPhase());
        }
    }

    public static void main(String[] args) {
        new PhaserTest().run();
    }


}
